package com.qf.commons.core.log;

import org.slf4j.MDC;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * author Ken
 * create_time 2022/11/12
 */
public class LogginMDCListener implements GenericApplicationListener {

    @Override
    public boolean supportsEventType(ResolvableType eventType) {
        //判断当前的事件类型是否为需要的订阅的事件类型
        return eventType.isAssignableFrom(ApplicationEnvironmentPreparedEvent.class);
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {

        ApplicationEnvironmentPreparedEvent environmentEvent = (ApplicationEnvironmentPreparedEvent) event;
        //获取当前SpringBoot加载好的环境
        ConfigurableEnvironment environment = environmentEvent.getEnvironment();
        //获取环境配置
        String microName = environment.getProperty("spring.application.name");
        if (microName != null) {
            //放入MDC
            MDC.put("fileName", microName);
        }
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 19;
    }
}
